﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using Silvermoon.Controls;
using Silvermoon.OpenGL;
using Silvermoon.Windows.Styles;
using System.Drawing;
using Passwords.Models;
using Passwords.Controllers;
using Silvermoon.Windows;
using Passwords.Pages;
using Passwords.Utils;
using System.Threading;
using Silvermoon.Shapes;
using Silvermoon.Images;
using Silvermoon.UI;
using Silvermoon.Controls.Base;
using System.Diagnostics;
using Passwords.Biz;
using Silvermoon.Controls.Forms;
using Passwords.Images;
using Silvermoon.Animations;
using Silvermoon.OpenGL.Native;

namespace Passwords
{
    public class LoginPage : Page
    {
        #region color animation

        static readonly Color[] GradientColors = new Color[] { PhoneColors.Lime, PhoneColors.Orange, PhoneColors.Yellow, PhoneColors.Blue };

        public static PropertyAccessor<LoginPage, Color> GradientColorProperty = PropertyAccessor.Register<LoginPage, Color>("GradientColor", c => c.GradientColor, (c, v) => c.GradientColor = v);

        private ColorTransition ct;

        public Color GradientColor
        {
            get
            {
                GlColor col = bgShape.GradientStops[1].Color;
                col.SwapRB();
                return col;
            }
            set
            {
                if (GradientColor != value)
                {
                    GlColor glColor = value;
                    glColor.SwapRB();
                    bgShape.GradientStops[1].Color = glColor;
                    bgShape.Update();
                    Invalidate(InvalidationFlag.Transformation);
                }
            }
        }

        private void StartColorAnimation()
        {
            Background = bgShape;
            ct = new ColorTransition { Duration = 4000, To = GradientColors[gradientColorIndex], EasingFunction = new PowerEase { Mode = EasingMode.EaseInOut, Power = 10 } };
            ct.Completed += new EventHandler(ct_Completed);
            gradientColorIndex++;
            if (gradientColorIndex >= GradientColors.Length) gradientColorIndex = 0;
            GradientColorProperty.Animate(this, ct);
        }

        void ct_Completed(object sender, EventArgs e)
        {
            StartColorAnimation();
        }

        #endregion

        public static Command OkCommand = new Command();
        public static Command CancelCommand = new Command();

        //private static FontSprite cachedFont;
        private int gradientColorIndex = 1;
        private Toolbar toolbar;
        private AnimatedControl busyControl;
        private ProgressingControl progressing;
        private PasswordBox passwordBox;
        private Label label;
        private Button okBtn, cancelBtn;
        private GradientStopShape bgShape;
        const int top = 36;

        public LoginPage()
            : base()
        {
            InitializeWindow();
            LoginController vm = new LoginController(this, 0);
        }

        protected override void Dispose(bool dispose)
        {
            if (ct != null)
            {
                ct.Completed -= ct_Completed;
                ct = null;
            }
            if (toolbar != null) toolbar.Dispose();
            base.Dispose(dispose);
        }

        private void InitializeWindow()
        {
            Color = Color.Black;
            const int bs = 16;
            Title = "LOGIN";
            Styles = StylePool.Metro;
            label = new Label { Margin = new Margin(bs, bs + top, bs, null), Height = 64, Alignment = Alignment.Near, LineAlignment = Alignment.Center, Text = "Enter your password:" };
            passwordBox = new PasswordBox { Margin = new Margin(bs, 80 + top, bs, null), Height = 64};
            progressing = new ProgressingControl { Margin = new Margin(0, null, 0, 0) };
            busyControl = new AnimatedControl { Size = new Size(128, 128), Margin = new Margin(true, true), Visible = false };
            Decorator busyContainer = new Decorator { Margin = new Margin(0, 320 + 64, 0, 0), Control = busyControl };

            Controls.Add(label, passwordBox, progressing);


            okBtn = new Button { Size = new Size(200, 64), Content = "Login", IsFocusable = false, Margin = new Margin(false, true) { Right = 8 }, Command = OkCommand };
            cancelBtn = new Button { Size = new Size(200, 64), Content = "Exit", IsFocusable = false, Margin = new Margin(false, true) { Left = 8 }, Command = CancelCommand };
            StackPanel panel = new StackPanel { Margin = new Margin(0, 280, 0, null), Height = 64, Orientation = StackPanelOrientation.Horizontal };
            panel.Controls.Add(okBtn, cancelBtn);


            Style = StylePool.Login;

            bgShape = new GradientStopShape(0, 3,

                                        new GradientStop(0, 255, 0, 0, 0),
                                        new GradientStop(1, PhoneColors.Lime),
                                        new GradientStop(2, 255, 0, 0, 0),
                                        new GradientStop(3, 255, 0, 0, 0)
                                        );

            Background = bgShape;

            cancelBtn.Tap += (s, e) =>
            {
                passwordBox.Text = "";
                passwordBox.Focus();
            };
            Controls.Add(panel, busyContainer);


            toolbar = new Toolbar();
            toolbar.Styles.SetClass<MenuItem>(new TextItemStyle { Font = FontCache.MediumRegularFont, Padding = new Margin(20, 0, 20, 0) });
#if DEBUG
            toolbar.Buttons.Add(new ToolbarButton { Content = ImagePool.Features, Command = PasswordCommands.Debug });
#endif
            toolbar.AddMenuItem("Change Password");
            toolbar.AddMenuItem("Backup").Enabled = false;
            toolbar.AddMenuItem("Restore").Enabled = false;
            toolbar.IsMenuButtonVisible = true;
            toolbar.MenuItems[0].Tap += new EventHandler<TapEventArgs>(OnChangePassword);
        }

        void OnChangePassword(object sender, TapEventArgs e)
        {
            ChangePasswordPage page = new ChangePasswordPage();
            this.NavigateTo(page);
        }


        protected override void OnHiding()
        {
            StopBusy();
            base.OnHiding();
        }

        protected override void OnShowing()
        {
            Context.CloseCurrent();
            base.OnShowing();
            this.Toolbar = toolbar;
        }

        protected override void OnShown()
        {
            base.OnShown();
            IsKeyboardVisible = true;
            passwordBox.Focus();
            StartColorAnimation();
        }

        public string Password
        {
            get { return passwordBox.Text; }
            set { passwordBox.Text = value; }
        }

        public void FocusInput()
        {
            passwordBox.Focus();
            Window.IsKeyboardVisible = true;
        }

        protected override void OnEnabledChanged()
        {
            bool enabled = Enabled;
            base.OnEnabledChanged();
            okBtn.Enabled = enabled;
            cancelBtn.Enabled = enabled;
            passwordBox.Enabled = enabled;
            //busyControl.Visible = !enabled;
            progressing.Visible = !enabled;
            Toolbar = enabled ? toolbar : null;
        }

        public void StopBusy()
        {
            busyControl.Visible = false;
            progressing.Visible = false;
        }

        //public override void OnExitApplication()
        //{
        //    RaiseCommand(CancelCommand);
        //}
    }
}
